// 云函数入口文件
const cloud = require('wx-server-sdk')
const dayjs = require('dayjs')
dayjs.extend(require('dayjs/plugin/isoWeek'))

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async event => {
  const { _id, location, tags, limit = 50 } = event
  if (location && (!location.longitude || !location.latitude)) {
    throw new Error('invalid location')
  }

  const now = dayjs()
  const week = now.startOf('isoWeek').format('YYYY-MM-DD')
  let list = []
  if (location) {
    ;({ list } = await db
      .collection('promotion-cast')
      .aggregate()
      .geoNear({
        near: new db.Geo.Point(location.longitude, location.latitude),
        spherical: true,
        distanceField: 'promotion.store.distance',
        maxDistance: 100000,
        query: {
          _id,
          'promotion.tags': tags,
          week,
        },
        limit,
      })
      .end())
    if (!list.length) {
      ;({ list } = await db
        .collection('promotion-cast')
        .aggregate()
        .geoNear({
          near: new db.Geo.Point(location.longitude, location.latitude),
          spherical: true,
          distanceField: 'promotion.store.distance',
          query: {
            _id,
            'promotion.tags': tags,
            demo: true,
          },
          limit,
        })
        .end())
    }
  } else if (_id) {
    ;({ data: list } = await db
      .collection('promotion-cast')
      .where({ _id, week })
      .get())
  }

  return list
}
